<?php

namespace DStatistics\model;

use DStatistics\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model as EloquentModel;

class LaravelModel extends Model
{
    protected $query;

    /**
     * @var EloquentModel
     */
    protected $model;

    protected $modelClass;


    /**
     * 获取model对象.
     *
     * @return EloquentModel
     */
    public function model()
    {
        return $this->model ?: ($this->model = $this->createModel());
    }

    /**
     * @param  array  $data
     * @return EloquentModel
     */
    public function createModel(array $data = [])
    {
        $model = new $this->modelClass();

        if ($data) {
            $model->setRawAttributes($data);
        }

        return $model;
    }

    /**
     * @return Builder
     */
    private function getQuery()
    {
        if(!$this->query){
            $this->query = $this->model()->newQuery();
        }

        return $this->query;
    }

    /**
     * 创建新的条件
     * @return Builder
     */
    public function newQuery()
    {
        $this->query = $this->model()->newQuery();

        return $this->query;
    }


    /**
     * 增加条件
     *
     * @param $column
     * @param $operator
     * @param $value
     * @param $boolean
     * @return $this
     */
    public function where($column, $operator = null, $value = null, $boolean = 'and')
    {
        $this->query = $this->getQuery()->where($column, $operator, $value, $boolean);

        return $this;
    }

    /**
     * 增加区间条件
     * @param $column
     * @param array|null $value
     * @param $boolean
     * @return $this
     */
    public function whereBetween($column, array $value , $boolean = 'and'):self
    {
        $this->query = $this->getQuery()->whereBetween($column,  $value, $boolean);

        return $this;
    }


    /**
     * 进行统计查询
     * @param $field
     * @return int
     */
    public function count($field = '*'): int
    {
        return $this->getQuery()->count($field);
    }

}
